<!DOCTYPE html>
<html class="x-admin-sm">

<head>
    <meta charset="UTF-8">
    <title>宿舍管理系统</title>
    <meta name="renderer" content="webkit">
    <meta name="csrf-token" content="{{ csrf_token() }}" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
        content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi" />
    <link rel="stylesheet" href="{{ asset('css/font.css') }}">
    <link rel="stylesheet" href="{{ asset('css/xadmin.css') }}">
    <script src="{{ asset('lib/layui/layui.js') }}" charset="utf-8"></script>
    <script type="text/javascript" src="{{ asset('js/xadmin.js') }}"></script>
    <!--[if lt IE 9]>
    <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
    <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>

<body>
    <div class="x-nav">
        <span class="layui-breadcrumb">
            <a href="/home">首页</a>
            <a>
                <cite>楼栋列表</cite></a>
        </span>
        <a class="layui-btn layui-btn-small" style="line-height:1.6em;margin-top:3px;float:right"
            onclick="location.reload()" title="刷新">
            <i class="layui-icon layui-icon-refresh" style="line-height:30px"></i></a>
    </div>
    <div class="layui-fluid">
        <div class="layui-row layui-col-space15">
            <div class="layui-col-md12">
                <div class="layui-card">
                    <div class="layui-card-body ">
                        <form class="layui-form layui-col-space5">
                            <div class="layui-inline layui-show-xs-block">
                                <input type="text" name="search" placeholder="请输入名称" autocomplete="off"
                                    class="layui-input" value="{{ old('search') }}">
                            </div>
                            <div class="layui-inline layui-show-xs-block">
                                <button class="layui-btn" lay-submit="" lay-filter="search"><i
                                        class="layui-icon">&#xe615;</i></button>
                            </div>
                        </form>
                    </div>
                    <div class="layui-card-body layui-table-body layui-table-main">
                        <table id="test" lay-filter="test"></table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-primary layui-btn-sm" lay-event="add">
            <i class="layui-icon">&#xe654;</i>
        </button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" lay-event="update">
            <i class="layui-icon">&#xe642;</i>
        </button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" lay-event="delete">
            <i class="layui-icon">&#xe640;</i>
        </button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" lay-event="sort">
            排序
        </button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" lay-event="generate">
            生成宿舍
        </button>
    </div>
</script>
<script>
    layui.use(['form', 'table'], function() {
        var table = layui.table;

        //第一个实例
        table.render({
            elem: '#test',
            url: '/buildings' //数据接口
                ,
            page: true //开启分页
                ,
            toolbar: '#toolbarDemo',
            cols: [
                [ //表头
                    {
                        type: 'checkbox'
                    }, {
                        field: 'id',
                        title: 'ID',
                        width: 80,
                        sort: true,
                        hide: true
                    }, {
                        field: 'company.name',
                        title: '公司',
                        width: 100,
                        templet: function(d) {
                            return d.company.short_name || d.company.name;
                        },
                        hide: {{ Auth::user()->is_super ? 'false' : 'true' }}
                    }, {
                        field: 'name',
                        title: '楼栋',
                        width: 80,
                        sort: true
                    }, {
                        field: 'short_name',
                        title: '简称',
                        width: 80,
                        sort: true
                    }, {
                        field: 'block',
                        title: '分区',
                        width: 60,
                        hide: true
                    }, {
                        field: 'dorm_type',
                        title: '宿舍类型',
                        width: 100,
                        sort: true,
                        templet: function(d) {
                            return d.dorm_type?.name || '';
                        }
                    }, {
                        field: 'record_order',
                        title: '抄表顺序',
                        width: 100,
                        sort: true,
                        hide: true
                    }, {
                        field: 'unit_name_type',
                        title: '单元名类型',
                        width: 120,
                        hide: true
                    }, {
                        field: 'unit_count',
                        title: '单元数',
                        width: 80
                    }, {
                        field: 'floors',
                        title: '层数',
                        width: 60
                    }, {
                        field: 'rooms_per_floor',
                        title: '单元层房间数',
                        width: 120,
                        sort: true
                    }, {
                        field: 'beds_per_room',
                        title: '每间可入住',
                        width: 120,
                        sort: true
                    }, {
                        field: 'gen_dorm_rule',
                        title: '生成宿舍规则',
                        width: 180,
                        sort: true
                    }, {
                        field: 'remark',
                        title: '备注',
                        width: 100
                    }, {
                        field: 'created_at',
                        title: '创建时间',
                        width: 135,
                        sort: true
                    }, {
                        field: 'update_at',
                        title: '更新时间',
                        width: 135,
                        sort: true,
                        hide: true
                    }
                ]
            ],
            parseData: function(res) {
                return {
                    "code": 0,
                    "msg": "",
                    "count": res.data.length,
                    "data": res.data
                }
            }
        });

        //监听头工具栏事件
        table.on('toolbar(test)', function(obj) {
            let checkStatus = table.checkStatus(obj.config.id);
            let data = checkStatus.data; //获取选中的数据
            switch (obj.event) {
                case 'add':
                    xadmin.open('添加楼栋', '{{ route('buildings.create') }}')
                    break;
                case 'update':
                    if (data.length === 0) {
                        layer.msg('请选择一行');
                    } else if (data.length > 1) {
                        layer.msg('只能同时编辑一个');
                    } else {
                        xadmin.open('更新楼栋', `/buildings/${data[0].id}/edit`)
                    }
                    break;
                case 'delete':
                    if (data.length === 0) {
                        layer.msg('请选择一行');
                    } else {
                        layer.confirm('确认要删除吗？', function(index) {
                            //发异步删除数据
                            data.forEach(t => {
                                del_one(null, t.id);
                            });
                            layer.close(index);
                            table.reload('test', {});
                        });
                    }
                    break;
                case 'sort':
                    xadmin.open('抄表顺序', '{{ route('buildings.order.sort') }}')
                    break;
                case 'generate':
                    if (data.length === 0) {
                        layer.msg('请选择一行');
                    } else if (data.length > 1) {
                        layer.msg('只能同时生成一栋');
                    } else {
                        if (data[0].dorm_type_id) {
                            if (check_gen_rule(data[0].gen_dorm_rule)) {
                                layer.confirm('生成宿舍将会将原有宿舍删除，原来分配宿舍的人员需重新分配，是否继续？', function(index) {
                                    layer.close(index);
                                    gen_dorms(data[0].id);
                                });

                            }
                        } else {
                            layer.msg('必须设置宿舍类型');
                        }
                    }
                    break;
            };
        });

        let form = layui.form;
        form.on('submit(search)', function(data) {
            console.log(data)
            table.reload('test', {
                url: '/buildings',
                where: data.field
            });
            return false;
        });


    });

    function check_gen_rule(rule) {
        if (rule == null || rule.trim().length == 0) {
            layui.layer.msg('生成规则不能为空，请设置该楼栋的宿舍生成规则！');
            return false;
        } else {
            if (rule.toString().indexOf('{简称}') == -1 && rule.toString().indexOf('{楼栋}') == -1) {
                layui.layer.msg('规则必须包含{简称} 或 {楼栋} 其中一个');
                return false;
            }
            if (rule.toString().indexOf('{楼层}') == -1) {
                layui.layer.msg('规则必须包含{楼层}');
                return false;
            }
            if (rule.toString().search(/{流水号:0+}/g) == -1) {
                layui.layer.msg('规则必须包含{流水号:0}或{流水号:00}或{流水号:000}');
                return false;
            }
        }
        return true;
    }

    function gen_dorms(id) {
        let index = layui.layer.load();
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $.ajax({
            url: `buildings/${id}/gen_dorms`,
            type: 'POST',
            dataType: "json",
            statusCode: {
                401: function() {
                    console.log("statusCode 401 called");
                    window.location.reload();
                },
                449: function() {
                    console.log("statusCode 449 called");
                }
            },
            success: function(d) {
                if (d.error) {
                    layui.layer.msg('生成失败:' + d.message, {
                        icon: 2,
                        time: 3000
                    });
                } else {
                    layui.layer.msg(`生成成功`, {
                        icon: 1,
                        time: 1000
                    });
                }
            },
            error: function(err) {
                console.log(err);
                layui.layer.msg('生成失败', {
                    icon: 2,
                    time: 3000
                });
            },
            complete: function() {
                layui.layer.close(index);
            }
        });
    }

    function del_one(obj, id) {
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $.ajax({
            url: '/buildings/' + id,
            type: 'DELETE',
            dataType: "json",
            statusCode: {
                401: function() {
                    console.log("statusCode 401 called");
                    window.location.reload();
                },
                449: function() {
                    console.log("statusCode 449 called");
                }
            },
            success: function() {
                layui.layer.msg(`已删除${id}!`, {
                    icon: 1,
                    time: 1000
                });
            },
            error: function(err) {
                layui.layer.msg('删除失败', {
                    icon: 2,
                    time: 1000
                });
            }
        });
    }
</script>

</html>
